from fastapi import FastAPI
from datetime import datetime
from pydantic import BaseModel, PositiveInt
import uvicorn

from terServerConfig import terSettings
from libs.dbutils import zndb
from libs.influxutils import tdb
from libs.znModbusTer import znModbusTer
from libs.mqutils import mqclient

print('start terminal server ...')

print('set db settings...')
# set db
dbSettings = terSettings['db']
zndb.setSettings(**dbSettings)
# set inluxdb
tdb.tdbSettings = terSettings['tdb']
# set mqtt
mqclient.host = terSettings['mq']['host']
mqclient.port = terSettings['mq']['port']
mqclient.uid = terSettings['mq']['uid']
mqclient.pwd = terSettings['mq']['pwd']
# load modbus datas
znModbusTer.dbCode = terSettings['db']['code']



app = FastAPI()
@app.get("/zn")
async def znRoot():
    return{
        "port": terSettings['server']['port']
    }
@app.get("/zn/startModbusTer")
async def znStartModbusTer():
    mqclient.start(True)
    znModbusTer.loadDatas()
    znModbusTer.start()
    return{
        "ac":"start zn modbus terminal."
    }
@app.get("/zn/vars")
async def znGetVars():
    res = [ znModbusTer.getVarInfo(x) for x in znModbusTer.dicts.variable.values()]
    return  res
@app.get("/zn/varDebug")
async  def znGetVarDebug(varId :int):
    res = znModbusTer.getVariableDebug(varId)
    return  res
if __name__ == "__main__":
    _port = terSettings['server']['port']
    uvicorn.run("terServer:app", host="0.0.0.0" , port=_port,  reload=True)
